package com.czkt.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.czkt.pojo.vo.SysUserVo;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

//@WebFilter(filterName = "AutoFilter",urlPatterns = "/*")
public class AutoFilter implements Filter {
    public void destroy() {
    }




    private   StringRedisTemplate stringRedisTemplate;

    public StringRedisTemplate getStringRedisTemplate() {
        return stringRedisTemplate;
    }

    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("进入了过滤器");

        HttpServletRequest request = (HttpServletRequest) req;

        HttpServletResponse response = (HttpServletResponse) resp;

        HttpSession session = request.getSession();
        Set<String> filterUrl=new HashSet<>();
//        filterUrl.add("/403");
        filterUrl.add("/");
        filterUrl.add("/doLogin");
        filterUrl.add("/logout");

        System.out.println( request.getRequestURI());
        System.out.println( request.getRequestURL());



        if((session.getAttribute("loginUser")!=null||stringRedisTemplate.opsForValue().get("loginUser")!=null) || filterUrl.contains(request.getServletPath())
                || request.getServletPath().endsWith(".css")  || request.getServletPath().endsWith(".ico")
        ){
            if(stringRedisTemplate.opsForValue().get("loginUser")!=null &&session.getAttribute("loginUser")==null ){

//                将字符串转换为json对象
                JSONObject sysUserVo= (JSONObject) JSON.parse( stringRedisTemplate.opsForValue().get("loginUser"));
                session.setAttribute("loginUser",sysUserVo );
            }
            System.out.println(session.getAttribute("loginUser"));
            chain.doFilter(req, resp);
        }else{
            response.sendRedirect("/");
        }


    }

    public void init(FilterConfig config) throws ServletException {

    }

}
